package com.example.project.projectspringcloud.controller.front.production;

import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Dictionary;
import com.example.project.projectspringcloud.entity.sys.SysConfig;
import com.example.project.projectspringcloud.entity.user.Collect;
import com.example.project.projectspringcloud.entity.user.Evaluate;
import com.example.project.projectspringcloud.entity.video.Video;
import com.example.project.projectspringcloud.service.sys.SysConfigService;
import com.example.project.projectspringcloud.service.sys.SysDictionaryService;
import com.example.project.projectspringcloud.service.user.UserCollectService;
import com.example.project.projectspringcloud.service.user.UserEvaluateService;
import com.example.project.projectspringcloud.service.video.VideoService;
import com.example.project.projectspringcloud.utils.RedisUtil;
import com.example.project.projectspringcloud.utils.TencentVideoUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

/**
 * 视频Controller
 *
 * @author Christopher Jones
 * @data 2018-08-14 14:38
 */
@Api(tags = "作品控制器")
@Controller
@RequestMapping(value = "/production")
public class ProductionController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(ProductionController.class);

    // 作品类型, 与码表一致
    private static Map<String, Integer> productionTypes = Maps.newHashMap();

    static {
        productionTypes.put("work", 1);
        productionTypes.put("lover", 2);
        productionTypes.put("celebrity", 3);
        productionTypes.put("promotional", 4);
    }

    @Autowired
    private VideoService videoService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private SysDictionaryService sysDictionaryService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserEvaluateService userEvaluateService;

    @Autowired
    private UserCollectService userCollectService;

    @ApiOperation(value = "作品列表", notes = "返回到作品列表页面")
    @GetMapping(value = {"", "/list"})
    public String list(@RequestParam("type") String type, Model model) throws Exception {
        // 获取工作类型作品
        Video video = new Video();
        video.setCollectUser(super.getCurrentUserId());
        video.setType(productionTypes.get(type));
        video.setOrderStr("video.count DESC");
        List<Video> videos = videoService.list(isMobile() ? new Page(0, 8) : new Page(0, 16), video);
        model.addAttribute("videos", new Page<Video>(videos));
        model.addAttribute("type", video.getType());
        if (productionTypes.get(type) == 1) {
            model.addAttribute("title", "网络音乐");
        }
        if (productionTypes.get(type) == 2) {
            model.addAttribute("title", "网络动漫");
        }
        if (productionTypes.get(type) == 3) {
            model.addAttribute("title", "网络演出剧");
        }
        if (productionTypes.get(type) == 4) {
            model.addAttribute("title", "网络表演");
        }
        if (getCurrentUser() != null) {
            // 获取收藏的作品
            List<Collect> collects = userCollectService.list(null, new Collect(getCurrentUser().getId(), 2));
            model.addAttribute("collects", collects);
        }

        return isMobile() ? "m/content/production/production-list" : "content/production/productions";
    }

    @ApiOperation(value = "获取作品详细", notes = "返回作品详细页面")
    @GetMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id") Integer id, Model model) {
        Video video = videoService.get(new Video(id));
        model.addAttribute("video", video);

        if (getCurrentUser() != null) {
            Collect collect = userCollectService.get(new Collect(getCurrentUser().getId(), 2, 2, id));
            model.addAttribute("collect", collect);

            Collect like = userCollectService.get(new Collect(getCurrentUser().getId(), 2, 1, id));
            model.addAttribute("like", like);
        }

        // 获取评价
        List<Evaluate> evaluates = userEvaluateService.list(null, new Evaluate(video.getId(), 6));
        model.addAttribute("evaluatesPage", new Page<Evaluate>(evaluates));

        List<Dictionary> dictionaries = sysDictionaryService.list(new Dictionary("evaluate-production-tags"), null);
        model.addAttribute("dictionaries", dictionaries);

        return isMobile() ? "m/content/production/production-detail" : "content/production/production-detail";
    }


    @ApiOperation(value = "API获取视频", notes = "通过视频ID获取视频api")
    @ApiImplicitParam(name = "videoId", value = "ID", required = true, dataType = "String", paramType = "query", example = "?videoId=123456")
    @GetMapping(value = "/api/play/{videoId}")
    @ResponseBody
    public RespBody play(@PathVariable("videoId") String videoId) throws Exception {
        Video video = videoService.get(new Video(Integer.valueOf(videoId)));
        if (StringUtils.isBlank(videoId) || video == null) {
            return RespBody.error("未找到该视频!");
        }

        List<SysConfig> sysConfigs = sysConfigService.list(null, new SysConfig("tencentcloud"));
        Video result = TencentVideoUtil.getTCPlayParam(video, false, sysConfigs, redisUtil, false);
        return RespBody.ok(result);
    }

    @ApiOperation(value = "API视频列表", notes = "获取api视频列表")
    @GetMapping(value = "/api/list")
    @ResponseBody
    public RespBody list(Video video, Page page) throws Exception {
        video.setCollectUser(super.getCurrentUserId());
        video.setOrderStr("video.count DESC");
        List<Video> videos = videoService.list(page, video);
        return RespBody.ok(new Page<Video>(videos));
    }

    @ApiOperation(value = "API增加视频播放量", notes = "增加视频播放量")
    @PostMapping(value = "/api/count/{videoId}")
    @ResponseBody
    public RespBody count(@PathVariable("videoId") Integer videoId) {
        try {
            videoService.count(videoId);
        } catch (Exception e) {
            logger.error("Add production count Failed!", e);
            return RespBody.error(translateI18N(e.getMessage()));
        }
        return RespBody.ok(true);
    }

    @ApiOperation(value = "API刷新失效视频缓存", notes = "刷新失效视频缓存")
    @GetMapping(value = "/api/refresh")
    @ResponseBody
    public RespBody refresh(Integer videoId) throws Exception {
        videoService.refresh(new Integer[]{videoId});
        return RespBody.ok(true);
    }
}
